/**
 * jims
 */
package com.jims.master.modules.csm.service;

import com.ckfinder.connector.utils.AccessControlUtil;
import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.ChineseCharToEnUtils;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.modules.csm.dao.*;
import com.jims.master.modules.csm.entity.*;
import com.jims.master.modules.sys.utils.DeptUtils;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 消耗品采购计划Service
 * @author DT
 * @version 2017-03-22
 */
@Service
@Transactional(readOnly = true)
public class ExpBuyPlanService extends CrudService<ExpBuyPlanDao, ExpBuyPlan> {
    @Autowired
    private ExpImportMasterService expImportMasterService;
    @Autowired
    private ExpExportService expExportService;
    @Autowired
    private ExpStockDao expStockDao;
    @Autowired
    private ExpExportDetailDao expExportDetailDao;
    @Autowired
    private ExpExportMasterDao expExportMasterDao;
    @Autowired
    private ExpImportDetailDao expImportDetailDao;
    @Autowired
    private ExpImportMasterDao expImportMasterDao;
    @Autowired
    private ExpPriceDao expPriceDao;
    @Autowired
    private ExpProvideApplicationDao expProvideApplicationDao;

    /**
     * 查询科室所提采购申请
     * @param page 分页对象
     * @param expBuyPlan
     * @return
     * @author fengyg
     * @date 2017-06-28
     */
    public Page<ExpBuyPlan> findPage(Page<ExpBuyPlan> page, ExpBuyPlan expBuyPlan) {
        ExpProvideApplication expProvideApplication = expBuyPlan.getExpProvideApplication();
        if(null != expProvideApplication){
            //List<ExpBuyPlan> list = dao.createExpBuyPlan(expProvideApplication.getStorageOut(), expBuyPlan.getStartDate(), expBuyPlan.getStopDate());
            DateFormat df = new SimpleDateFormat();
            List<ExpBuyPlan> list = dao.createExpBuyPlan(expProvideApplication.getStorageOut(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(expBuyPlan.getStartDate()),new SimpleDateFormat
                    ("yyyy-MM-dd:HH:mm:ss").format(expBuyPlan.getStopDate()));
            if(null != list && list.size() > 0){
                for (ExpBuyPlan buyPlan : list) {
                    if(null != buyPlan.getExpProvideApplication()){
                        buyPlan.setBuyQuantity(Double.valueOf(buyPlan.getBuyQuantity()) / buyPlan.getExpProvideApplication().getPackageNum() + "");
                    }
                }
            }
            page.setList(list);
        }else{
            page.setList(null);
        }
        expBuyPlan.setPage(page);
        return page;
	}

    /**
     * 保存消耗品采购计划(生成)
     * @param expBuyPlan
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public int saveExpBuyPlanCreate(ExpBuyPlan expBuyPlan){
        int num = 0;
        if(null != expBuyPlan){
            List<ExpBuyPlan> list = expBuyPlan.getExpBuyPlanList();
            String buyPlanNum = getBuyPlanNum();
            if(null != list && list.size() > 0){
                for(int i = 0; i < list.size(); i++){
                    ExpBuyPlan insertData = list.get(i);
                    insertData.preInsert();
                    insertData.updateOrgId();
                    insertData.setPurchaseOrder((i + 1) + "");
                    insertData.setPurchaseNumber(buyPlanNum);
                    insertData.setStorageDept(UserUtils.getUser().getOrgDept().getId());
                    insertData.setBuyer(UserUtils.getUser().getId());
                    insertData.setStartDate(expBuyPlan.getStartDate());
                    insertData.setStopDate(expBuyPlan.getStopDate());
                    insertData.setOutFlag("0");
                    int insert = dao.insert(insertData);
                    if(insert > 0){
                        num += insert;
                    }else{
                        return 0;
                    }
                }
            }else{
                return 0;
            }
        }
        return num;
    }

    /**
     * 生成采购单的单据号
     * @return
     * @author fengyg
     * @date 2017-07-18
     */
    public String getBuyPlanNum(){
        String documentNo = "";
        String deptName = DeptUtils.getDeptName(UserUtils.getUser().getOrgDept().getId(),"");
        deptName = ChineseCharToEnUtils.getAllFirstLetter(deptName);
        documentNo += deptName;
        DateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        documentNo += dateFormat.format(new Date());
        int i = dao.findDocumentNo(documentNo, UserUtils.getOrgId());
        String num = String.valueOf(i);
        String str ="0000";
        str=str.substring(0, 4-num.length())+num;
        documentNo += str;
        return documentNo;
    }

    /**
     * 根据采购单号查询消耗品采购单详情
     * @param expBuyPlan
     * @return
     * @author fengyg
     * @date 2017-07-18
     */
    public List<ExpBuyPlan> findByNumber(ExpBuyPlan expBuyPlan){
        expBuyPlan.updateOrgId();
        List<ExpBuyPlan> list = dao.findByNumber(expBuyPlan);
        if(null != list && list.size() > 0){
            for (ExpBuyPlan buyPlan : list) {
                ExpProvideApplication expProvideApplication = new ExpProvideApplication();
                expProvideApplication.setExpInfoId(buyPlan.getInfoId());
                buyPlan.setExpProvideApplication(expProvideApplication);
            }
        }
        return list;
    }

    /**
     * 根据采购单号查询科室申请耗材信息(采购对消入出库功能页面)
     * @param purchaseNumber 采购单号
     * @return
     * @author fengyg
     * @date 2017-07-19
     */
    public List findExpProvideApplicationByNumber(String purchaseNumber){
        Double totalMoney = 0.00;  //合计
        List<ExpBuyPlan> list = dao.findExpProvideApplicationByNumber(purchaseNumber, UserUtils.getUser().getOrgDept().getId(), UserUtils.getOrgId());
        if(null != list){
            for (ExpBuyPlan expBuyPlan : list) {
                if(null != expBuyPlan && null != expBuyPlan.getExpProvideApplication()){
                    expBuyPlan.getExpProvideApplication().setAuditQuantity(expBuyPlan.getExpProvideApplication().getAuditQuantity() / expBuyPlan.getExpProvideApplication().getPackageNum());
                }
                ExpPrice price = expBuyPlan.getExpPrice();
                ExpProvideApplication provideApplication = expBuyPlan.getExpProvideApplication();
                if(null != price && null != price.getRetailPrice()){
                    if(null != provideApplication && null != provideApplication.getAuditQuantity()){
                        totalMoney += price.getTradePrice() * provideApplication.getAuditQuantity();
                    }
                }
            }
            for (ExpBuyPlan buyPlan : list) {
                buyPlan.setTotalMoney(totalMoney);
            }
        }
        return list;
    }

    /**
     * 根据科室申请表ID查询科室申请某个耗材信息(采购对消入出库功能,右侧弹出页面修改指定行数据)
     * @param expBuyPlan
     * @return
     * @author fengyg
     * @date 2017-07-20
     */
    public ExpBuyPlan getByApplicationId(ExpBuyPlan expBuyPlan){
        if(null != expBuyPlan && null != expBuyPlan.getExpProvideApplication() && null != expBuyPlan.getExpProvideApplication().getId()){
            expBuyPlan.updateOrgId();
            expBuyPlan.getExpProvideApplication().setStorageOut(UserUtils.getUser().getOrgDept().getId());
            ExpBuyPlan returnBuyPlan = dao.getByApplicationId(expBuyPlan);
            if(null != returnBuyPlan && null != returnBuyPlan.getExpProvideApplication()){
                returnBuyPlan.getExpProvideApplication().setAuditQuantity(returnBuyPlan.getExpProvideApplication().getAuditQuantity() / returnBuyPlan.getExpProvideApplication().getPackageNum());
            }
            return returnBuyPlan;
        }
        return null;
    }

    /**
     * 保存采购对消入出库
     * @param expBuyPlan
     * @return
     * @author fengyg
     * @date 2017-07-21
     */
    @Transactional(readOnly = false)
    public int saveBuyPlanImpExp(ExpBuyPlan expBuyPlan){
        int num = 0;
        String supplier = "";
        if(null != expBuyPlan && expBuyPlan.getExpBuyPlanList().size() > 0){
            List<ExpBuyPlan> planList = expBuyPlan.getExpBuyPlanList();
            if(null != planList && planList.size() > 0){
                for (ExpBuyPlan buyPlan : planList) {
                    ExpStock stockEntity = buyPlan.getExpStock();
                    if(null != stockEntity && !StringUtils.isNotBlank(stockEntity.getBatchNo())){
                        return -2;
                    }
                }
            }
            String importMasterId = saveImportMasterDetail(planList);   //保存入库主记录、明细记录
            if(!StringUtils.isNotBlank(importMasterId)){
                return 0;
            }

            List<ExpProvideApplication> applicationList = new ArrayList<>();   //科室申请采购list集合

            String purchaseNumber = planList.get(0).getPurchaseNumber();  //采购单号
            Date exportDate = new Date();    //出库日期
            String exportClass = "";         //出库类别
            if(null != planList.get(0).getExpStock() && null != planList.get(0).getExpStock().getExpImportMaster()){
                exportDate = planList.get(0).getExpStock().getExpImportMaster().getImportDate();   //入库日期 = 出库日期
            }

            for (ExpBuyPlan buyPlan : planList) {
                String packageSpec = buyPlan.getPackageSpec();   //包装规格
                String packageUnit = buyPlan.getPackageUnit();   //包装单位
                ExpPrice expPrice = buyPlan.getExpPrice();   //价格表
                ExpProvideApplication expProvideApplication = buyPlan.getExpProvideApplication();  //科室申请表
                ExpStock expStock = buyPlan.getExpStock();    //库存表
                if(null != expStock){
                    supplier = expStock.getExpImportMaster().getSupplier();
                }
                if(!StringUtils.isNotBlank(expStock.getBatchNo())){   //批号为空
                    return -2;
                }
                expStock.setExpCode(expProvideApplication.getExpCode());
                expStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
                if(StringUtils.isNotBlank(expProvideApplication.getExpInfoId())){
                    expStock.setInfoId(expProvideApplication.getExpInfoId());
                }else{
                    expStock.setInfoId(expProvideApplication.getInfoId());
                }
                expStock.updateOrgId();
                List<ExpStock> oldStockList = expStockDao.findByBatchNo(expStock);    //查询库存里是否有该批号的耗材
                ExpStock oldStock = new ExpStock();
                if(null != oldStockList && oldStockList.size() > 0){  //已经存在的该批号库存信息
                    oldStock = oldStockList.get(0);
                }else{   //库存里没有该批号的库存信息
                    oldStock.setQuantity(0.00);
                }
                expProvideApplication.setPackageSpec(packageSpec);
                expProvideApplication.setPackageUnits(packageUnit);
                expProvideApplication.setRemarks(expStock.getBatchNo());    //科室申请采购表的remarks备注字段，暂时作为批号的暂存字段
                expProvideApplication.setUpdateDate(expStock.getExpireDate());  //科室申请采购表的updateDate字段，暂时作为有效期的暂存字段
                expProvideApplication.setExpName(expStock.getSterilizationMethod());  //科室申请实体类的expName字段，暂时作为灭菌方式的暂存字段
                expProvideApplication.setStorageName(expStock.getSterilizationBatchNo());  //科室申请实体类的firmId字段，暂时作为灭菌批号的暂存字段
                expProvideApplication.setCreateDate(expStock.getSterilizationDate());  //科室申请实体类的createDate字段，暂时作为灭菌日期的暂存字段
                expProvideApplication.setTotalPrice(String.valueOf(expPrice.getTradePrice()));  //科室申请实体类的totalPrice字段，暂时作为进价的暂存字段
                if(oldStock.getQuantity() - 0.00 > 0.00){
                    expProvideApplication.setQuantityOut(oldStock.getQuantity());    //科室申请采购表的quantityOut字段，暂时作为出库后库存数的暂存字段
                }else{
                    expProvideApplication.setQuantityOut(0.00);  //科室申请采购表的quantityOut字段，暂时作为出库后库存数的暂存字段
                }
                applicationList.add(expProvideApplication);
                if(null != expStock && null != expStock.getExpExportMaster() && exportClass.trim().equals("")){
                    exportClass = expStock.getExpExportMaster().getExportClass();   //出库类别赋值
                }
                //更改科室申请信息的状态为已发放
                if(!StringUtils.isNotBlank(expProvideApplication.getExpInfoId())){
                    expProvideApplication.setExpInfoId(expProvideApplication.getInfoId());
                }
                expProvideApplication.setQuantityOut(expProvideApplication.getAuditQuantity() * expProvideApplication.getPackageNum());
                expProvideApplication.setOutFlag("2");
                int updateApplicationNum = expProvideApplicationDao.updateProvideApplication(expProvideApplication);
                if (updateApplicationNum > 0) {
                    num += updateApplicationNum;
                }else{
                    return 0;
                }
            }
            int totalExportNum = saveExportMasterDetail(applicationList,exportClass,exportDate);  //保存出库主记录、出库明细
            if(totalExportNum > 0){
                num += totalExportNum;
            }else{
                return totalExportNum;
            }

            //判断科室申请的耗材是否都发放完毕，如果都发完，更改采购计划表状态
            int i = updateBuyPlanOutFlag(purchaseNumber, supplier, importMasterId);
            if(i > 0){
                num += i;
            }else{
                return 0;
            }
        }else{
            return -1;  //没有数据需要保存
        }
        return num;
    }

    /**
     * 保存采购对消入库的入库主记录、明细；新增或更新库存信息
     * @param buyPlanList
     * @return importMasterId 返回入库主记录ID，目的是调用updateBuyPlanOutFlag()方法更改采购表发放状态
     * @author fengyg
     * @date 2017-07-22
     */
    @Transactional(readOnly = false)
    public String saveImportMasterDetail(List<ExpBuyPlan> buyPlanList){
        int num = 0;
        String importMasterId;
        if(null != buyPlanList.get(0).getExpStock() && null != buyPlanList.get(0).getExpStock().getExpImportMaster()){
            Double accountReceivable = 0.00;    //入库应付款
            ExpImportMaster importMaster = buyPlanList.get(0).getExpStock().getExpImportMaster();   //入库主记录
            importMaster.preInsert();
            importMaster.setStorageId(UserUtils.getUser().getOrgDept().getId());
            importMaster.updateOrgId();
            importMaster.setDocumentNo(expImportMasterService.createDocumentNo(importMaster));
            if(StringUtils.isNotBlank(importMaster.getImportClass())){
                importMaster.setImportClass(DictUtils.getDictLabel(importMaster.getImportClass(),"EXP_STOTARG_TYPE",""));  //入库类别转换
            }else{
                return null;    //入库类别为空
            }
            for(int i = 0; i < buyPlanList.size(); i++){
                ExpBuyPlan buyPlan = buyPlanList.get(i);
                ExpPrice expPrice = buyPlan.getExpPrice();
                ExpProvideApplication provideApplication = buyPlan.getExpProvideApplication();  //科室申请采购记录
                ExpStock expStock = buyPlanList.get(i).getExpStock();
                if(!StringUtils.isNotBlank(expStock.getBatchNo())){   //批号为空
                    return null;
                }
                expStock.setExpCode(provideApplication.getExpCode());
                expStock.setStorageId(UserUtils.getUser().getOrgDept().getId());
                if(StringUtils.isNotBlank(provideApplication.getExpInfoId())){
                    expStock.setInfoId(provideApplication.getExpInfoId());
                }else{
                    expStock.setInfoId(provideApplication.getInfoId());
                }
                expStock.updateOrgId();
                List<ExpStock> oldStockList = expStockDao.findByBatchNo(expStock);    //查询库存里是否有该批号的耗材
                if(null != oldStockList && oldStockList.size() > 0){  //已经存在的该批号库存信息
                }else{   //库存里没有该批号的库存信息
                   //插入一条新的库存数量为0的信息
                   expStock.preInsert();
                   expStock.setPackageNum(provideApplication.getPackageNum() + "");
                   expStock.setPackageSpec(buyPlan.getPackageSpec());
                   expStock.setPackageUnits(buyPlan.getPackageUnit());
                   expStock.setMinSpec(provideApplication.getMinSpec());
                   expStock.setMinUnits(provideApplication.getMinUnits());
                   expStock.setPurchasePrice(expPrice.getTradePrice());
                   expStock.setDiscount("1");
                   expStock.setQuantity(0.00);    //采购对消入出库，库存数为0
                   expStock.setDocumentNo(importMaster.getDocumentNo());
                   expStock.setImportMasterId(importMaster.getId());
                    int insertStock = expStockDao.insert(expStock);  //新增库存数量为0的库存信息
                    if(insertStock > 0){
                        num += insertStock;
                    }else{
                        return null;
                    }
                }

                ExpImportDetail importDetail = new ExpImportDetail();  //入库明细记录
                importDetail.preInsert();
                importDetail.setMasterId(importMaster.getId());
                importDetail.setItemNo((i + 1) + "");
                importDetail.setExpCode(provideApplication.getExpCode());
                if(StringUtils.isNotBlank(provideApplication.getExpInfoId())){
                    importDetail.setInfoId(provideApplication.getExpInfoId());  //科室申请采购表中，发放时infoId不为空，那么，入库明细里infoId为发放时infoId
                }else{
                    importDetail.setInfoId(provideApplication.getInfoId());
                }
                importDetail.setPackageNum(provideApplication.getPackageNum() + "");
                importDetail.setPackageSpec(buyPlanList.get(i).getPackageSpec());
                importDetail.setPackageUnits(buyPlanList.get(i).getPackageUnit());
                importDetail.setMinSpec(provideApplication.getMinSpec());
                importDetail.setMinUnits(provideApplication.getMinUnits());
                importDetail.setPurchasePrice(buyPlanList.get(i).getExpPrice().getTradePrice());
                importDetail.setDiscount("1");
                importDetail.setBatchNo(expStock.getBatchNo());
                importDetail.setExpireDate(expStock.getExpireDate());
                importDetail.setSterilizationMethod(expStock.getSterilizationMethod());
                importDetail.setSterilizationBatchNo(expStock.getSterilizationBatchNo());
                importDetail.setSterilizationDate(expStock.getSterilizationDate());
                importDetail.setQuantity(provideApplication.getAuditQuantity() * provideApplication.getPackageNum() + "");
                importDetail.updateOrgId();
                int insertImportDetailNum = expImportDetailDao.insert(importDetail);   //保存入库明细记录
                if(insertImportDetailNum > 0){
                    num += insertImportDetailNum;
                }else{
                    return null;
                }
                accountReceivable += importDetail.getPurchasePrice() * provideApplication.getAuditQuantity();   //计算入库应付款
            }
            importMaster.setAccountReceivable(accountReceivable);
            int insertMasterNum = expImportMasterDao.insert(importMaster);   //保存入库主记录
            if(insertMasterNum > 0){
                num += insertMasterNum;
                importMasterId = importMaster.getId();
            }else{
                return null;
            }
        }else{
            return null;   //入库主记录为空，保存失败
        }
        if(num > 0){
            return importMasterId;
        }
        return importMasterId;
    }

    /**
     * 保存采购对消入出库的出库主记录、明细记录
     * @param list  科室申请采购list集合
     * @return
     * @author fengyg
     * @date 2017-07-21
     */
    @Transactional(readOnly = false)
    public int saveExportMasterDetail(List<ExpProvideApplication> list,String exportClass,Date exportDate){
        int num = 0;
        Map<String, List<ExpProvideApplication>> map = getExportMasterDetailMap(list);
        if(map.isEmpty()){   //map集合为空，没有需要保存的数据
            return -1;
        }
        Set<String> keySets = map.keySet();  //key集合(所有出库主记录的收货方ID集合)
        for (String receiver : keySets) {
            Double accountReceivable = 0.00;   //出库应收款
            ExpExportMaster exportMaster = new ExpExportMaster();  //出库主记录
            exportMaster.preInsert();
            exportMaster.updateOrgId();
            exportMaster.setStorageId(UserUtils.getUser().getOrgDept().getId());
            exportMaster.setExportClass(DictUtils.getDictLabel(exportClass,"EXP_STOTARG_TYPE",""));   //出库类别翻译并设值
            exportMaster.setExportDate(exportDate);
            exportMaster.setReceiver(receiver);
            exportMaster.setDocumentNo(expExportService.createDocumentNo(exportMaster));
            exportMaster.setAccountType("");
            List<ExpProvideApplication> exportDetailList = map.get(receiver);   //出库明细记录集合
            for (int i = 0; i < exportDetailList.size(); i++) {
                ExpProvideApplication expProvideApplication = exportDetailList.get(i);
                ExpExportDetail exportDetail = new ExpExportDetail();  //出库明细记录
                exportDetail.preInsert();
                exportDetail.setMasterId(exportMaster.getId());
                exportDetail.setItemNo((i+1) + "");
                if (StringUtils.isNotBlank(expProvideApplication.getExpInfoId())) {  //科室申请采购表中，发放时infoId不为空，那么，出库明细里infoId为发放时infoId
                    exportDetail.setInfoId(expProvideApplication.getExpInfoId());
                }else{
                    exportDetail.setInfoId(expProvideApplication.getInfoId());
                }
                exportDetail.setExpCode(expProvideApplication.getExpCode());
                exportDetail.setPackageNum(expProvideApplication.getPackageNum() + "");
                exportDetail.setPackageSpec(expProvideApplication.getPackageSpec());
                exportDetail.setPackageUnits(expProvideApplication.getPackageUnits());
                exportDetail.setMinSpec(expProvideApplication.getMinSpec());
                exportDetail.setMinUnits(expProvideApplication.getMinUnits());
                exportDetail.setBatchNo(expProvideApplication.getRemarks());  //科室申请采购表的remarks备注字段暂存着批号信息
                exportDetail.setExpireDate(expProvideApplication.getUpdateDate());  //科室申请采购表的updateDate字段暂存着有效期信息
                exportDetail.setSterilizationMethod(expProvideApplication.getExpName()); //科室申请实体类的expName字段暂存着灭菌方式信息
                exportDetail.setSterilizationBatchNo(expProvideApplication.getStorageName());  //科室申请实体类的firmId字段暂存着灭菌批号信息
                exportDetail.setSterilizationDate(expProvideApplication.getCreateDate());  //科室申请实体类的createDate字段暂存着灭菌日期信息
                exportDetail.setDiscount("1");
                exportDetail.setQuantity(expProvideApplication.getAuditQuantity() * expProvideApplication.getPackageNum());
                //exportDetail.setInventory(expProvideApplication.getQuantityOut());   //科室申请采购表的quantityOut字段，暂存着出库后库存数信息
                exportDetail.updateOrgId();

                ExpStock stock = new ExpStock();
                stock.setExpCode(exportDetail.getExpCode());
                stock.updateOrgId();
                stock.setStorageId(UserUtils.getUser().getOrgDept().getId());
                stock.setInfoId(exportDetail.getInfoId());
                stock.setBatchNo(exportDetail.getBatchNo());
                List<ExpStock> stockList = expStockDao.findByBatchNo(stock);
                if(null != stockList && stockList.size() > 0){
                    stock = stockList.get(0);
                }
                exportDetail.setInventory(stock.getQuantity());   //设置出库后库存数

                ExpPrice price = new ExpPrice();
                ExpInfo info = new ExpInfo();
                info.setId(exportDetail.getInfoId());
                price.setExpInfo(info);
                price.setPackageSpec(exportDetail.getPackageSpec());
                ExpPrice expPrice = expPriceDao.getPriceByInfoPackageSpec(price);
                exportDetail.setPurchasePrice(expPrice.getRetailPrice());
                accountReceivable += expPrice.getRetailPrice() * expProvideApplication.getAuditQuantity();   //计算出库应收款

                int insertExportDetailNum = expExportDetailDao.insert(exportDetail);  //保存采购对消出库明细记录
                if(insertExportDetailNum > 0){
                    num += insertExportDetailNum;
                }else{
                    return 0;
                }
            }
            exportMaster.setAccountReceivable(accountReceivable);  //出库主记录应收款赋值
            int insertExportMasterNum = expExportMasterDao.insert(exportMaster);   //保存采购对消出库主记录
            if(insertExportMasterNum > 0){
                num += insertExportMasterNum;
            }else{
                return 0;
            }
        }
        return num;
    }

    /**
     * 根据传递过来的科室申请采购list集合，拼装出库主记录、明细记录
     * map的key是出库主记录的收货方ID(字符串)，value是出库明细
     * @param list
     * @return
     * @author fengyg
     * @date 2017-07-21
     */
    @Transactional(readOnly = false)
    public Map<String,List<ExpProvideApplication>> getExportMasterDetailMap(List<ExpProvideApplication> list){
        Map<String,List<ExpProvideApplication>> map = new HashMap<>();
        if(null != list && list.size() > 0){
            for (ExpProvideApplication expProvideApplication : list) {
                if(map.containsKey(expProvideApplication.getStorageIn())){   //map集合的key里有出库主记录的收货方字段
                    List<ExpProvideApplication> mapValueList = map.get(expProvideApplication.getStorageIn());
                    mapValueList.add(expProvideApplication);
                }else{      //map里没有指定的key
                    List<ExpProvideApplication> newMapValueList = new ArrayList<>();
                    newMapValueList.add(expProvideApplication);
                    map.put(expProvideApplication.getStorageIn(),newMapValueList);
                }
            }
        }
        return map;
    }

    /**
     * 更新采购表状态
     * 先判断科室申请耗材是否都发放完毕，如果都发放完，那么更新采购表状态
     * @param purchaseNumber  采购单号
     * @return
     * @author fengyg
     * @date 2017-07-23
     */
    @Transactional(readOnly = false)
    public int updateBuyPlanOutFlag(String purchaseNumber,String supplier,String importMasterId){
        boolean outFlag = true;  //全部发放判断标志
        int num = 1;
        Date startDate = new Date();
        Date stopDate = new Date();
        ExpBuyPlan buyPlan = new ExpBuyPlan();
        if(!StringUtils.isNotBlank(purchaseNumber)){
            return 0;
        }
        buyPlan.setPurchaseNumber(purchaseNumber);
        buyPlan.updateOrgId();
        List<ExpBuyPlan> buyPlanList = dao.findByNumber(buyPlan);
        if(null != buyPlanList && buyPlanList.size() > 0){
            startDate = buyPlanList.get(0).getStartDate();
            stopDate = buyPlanList.get(0).getStopDate();
        }
        ExpProvideApplication application = new ExpProvideApplication();
        application.updateOrgId();
        application.setStorageOut(UserUtils.getUser().getOrgDept().getId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startDate1 = sdf.format(startDate);
        String stopDate1 = sdf.format(stopDate);
        application.setStartDate(startDate1);
        application.setStopDate(stopDate1);
        List<ExpProvideApplication> applicationList = expProvideApplicationDao.searchProvideApplication(application);
        if(null != applicationList && applicationList.size() > 0){
            for (ExpProvideApplication provideApplication : applicationList) {
                if(!provideApplication.getOutFlag().equals("2")){
                    outFlag = false;
                }
            }
        }else{
            return 0;
        }
        if(outFlag){  //全部发放
            int i = dao.updateBuyPlanOutFlag(purchaseNumber, supplier, importMasterId);
            if(i > 0){
                num += i;
            }else{
                return 0;
            }
        }
        return num;
    }
}